package com.pine.app.module.security.oauth.plugin.impl.loginAttemp;


import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.pine.app.module.security.oauth.config.properties.LoginProperties;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author xyjxust
 * @create 2018/11/15 17:35
 **/

public class InMemoryLoginAttemptServiceImpl implements LoginAttempService{

    private LoadingCache<String, Integer> attemptsCache;
    private LoginProperties oauthProperty;
    public InMemoryLoginAttemptServiceImpl(LoginProperties oauthProperty) {
        super();
        attemptsCache = CacheBuilder.newBuilder().
                expireAfterWrite(oauthProperty.getAttemp().getExpire(), TimeUnit.MILLISECONDS).build(new CacheLoader<String, Integer>() {
            public Integer load(String key) {
                return 0;
            }
        });
        this.oauthProperty = oauthProperty;
    }

    public void loginSucceeded(String key) {
        attemptsCache.invalidate(key);
    }

    public void loginFailed(String key) {
        int attempts = 0;
        try {
            attempts = attemptsCache.get(key);
        } catch (ExecutionException e) {
            attempts = 0;
        }
        attempts++;
        attemptsCache.put(key, attempts);
    }

    public boolean isBlocked(String key) {
        try {
            return attemptsCache.get(key) >= oauthProperty.getAttemp().getTimers();
        } catch (ExecutionException e) {
            return false;
        }
    }
    public  int loginTimes(String key) {
        try {
            return attemptsCache.get(key);
        } catch (ExecutionException e) {
            return 0;
        }
    }
}
